<script setup>
import 'jiuqi-ui';
import {computed, inject, reactive, ref, watch } from "vue";
import '../common/iconfont'
//================================================【组件通信】============================================================
//后端请求方法
const context = inject('context')
//重新审核按钮 失效控制
const reCheckDisable = inject('reCheckDisable')
//导出按钮 失效控制
const exportDisable = inject('exportDisable')
//分摊审核请求参数（同步 时期参数、单位参数） 和 结果类型
const dataCheckReqParam = inject('dataCheckReqParam')
//当前 分摊审核 结果类型
const dataCheckResType = inject('dataCheckResType')
//暴露 轮询进度 方法
defineExpose({
    pollingProgress
});
//================================================【公用相关】============================================================
//进度条数值
const calculateProgress = ref(0)
//当前单位、当前时期 下是否匹配了模型
const isMatchModel = ref(false)
// 查询审核信息是否结束
const isGetMessageEnd = ref(false)
//选择单位后，当前时期、单位有匹配模型，该模型执行过分摊，展示模型名称和计算时间
const modelAndCalculateInfo = reactive({modelTitle: '', calculateTime: ''})
//================================================【组件属性】============================================================
const processedDataCheckReqParam = computed(() => {
    // 对 监听对象 进行深拷贝，以避免出现 newValue 和 oldValue 一致的情况
    return JSON.parse(JSON.stringify(dataCheckReqParam))
})
watch(processedDataCheckReqParam, async (newValue, oldValue) => {
    //当 请求参数 改变时
    if (oldValue === undefined || newValue.nrUnitCode !== oldValue.nrUnitCode || newValue.nrDateParam !== oldValue.nrDateParam) {
        //当 选择单位  为空时(防止下次 选择单位后 出现右侧内容闪烁)
        if (newValue.nrUnitCode === '') {
            //避免出现当前未匹配模型的页面
            isMatchModel.value = true;
            dataCheckResType.value = '';
            isGetMessageEnd.value = false;
            reCheckDisable.value = true;
        }

        //当时期参数、单位编码都存在时
        if (newValue.nrDateParam && newValue.nrUnitCode) {
            //检测 当前时期、当前单位 下是否匹配了模型
            await context.getPlugin('http').get(`abc/model/home/check/PeriodAndUnit/${newValue.nrDateParam}/${newValue.nrUnitCode}`).then(({data}) => {
                isMatchModel.value = data.checkResult
                //当前单位、当前时期下存在模型时，查询分摊结果
                if (isMatchModel.value) {
                    //当请求参数改变时，重新查询分摊结果
                    getCalculateResult(newValue);
                    //设置当前模型名称
                    modelAndCalculateInfo.modelTitle = data.modelBean.title
                } else {
                    reCheckDisable.value = true
                    exportDisable.value = true
                    dataCheckResType.value = 'OTHER'
                }
            })
        }
    }
}, {deep: true, immediate: true})
//================================================【普通方法】============================================================
//==================================================================【查询分摊结果】
function getCalculateResult() {
    context.getPlugin('http').get(`/abc/calculator/calculate/result/info/${dataCheckReqParam.nrDateParam}/${dataCheckReqParam.nrUnitCode}`).then(async ({data}) => {
        dataCheckResType.value = data.status

        //当存在模型，但未执行计算时，res.data 是null   res.data.status 是undefined
        if (dataCheckResType.value === undefined) {
            reCheckDisable.value = false
            exportDisable.value = true
        } else if (dataCheckResType.value === 'CALCULATING') {
            reCheckDisable.value = true
            exportDisable.value = true
            await pollingProgress(data.jobInstanceId);
        } else if (dataCheckResType.value === 'SUCCESS') {
            exportDisable.value = true
            reCheckDisable.value = false
        } else {
            await getCheckMessage(data.id);
        }

        modelAndCalculateInfo.calculateTime = data.startTime
    })
}

//==================================================================【获取数据审核结果数组(对于 警告、失败、取消 审核结果类型)】
const checkMessageArr = reactive([])

function getCheckMessage(resultBeanId) {
    isGetMessageEnd.value = false
    context.getPlugin('http').get(`abc/dataValidator/message/${resultBeanId}`).then(res => {
        checkMessageArr.splice(0, checkMessageArr.length, ...res.data.message)

        if (checkMessageArr.length > 0) {
            //控制 重新审核、导出 按钮可用
            exportDisable.value = false
            reCheckDisable.value = false
            dataCheckResType.value = 'WARNING'
        } else {
            //控制 导出按钮 失效
            exportDisable.value = true
            //控制 重新审核按钮 可用
            reCheckDisable.value = false
            dataCheckResType.value = 'ERROR'
        }

        isGetMessageEnd.value = true
    })
}

//==================================================================【不断获取最新计算进度(对于 计算中 审核结果类型)】
function pollingProgress(jobInstanceId) {
    //若父组件调用，需要手动设置 resultType 类型为 计算中
    dataCheckResType.value = 'CALCULATING'

    let timer = null
    const timerFunction = () => {
        timer = setTimeout(async function a() {
            let resDetail = null
            await context.getPlugin('http').get('/abc/calculator/calculate/result/detail/' + jobInstanceId).then(res => {
                resDetail = res.data
            })

            calculateProgress.value = resDetail.progress

            timer = setTimeout(a, 25)

            if (resDetail.state === '运行完毕') {
                clearTimeout(timer)
                await getCalculateResult()
                calculateProgress.value = 0
            }
        }, 25)
    }

    timerFunction()
}
//==================================================================【长字符 气泡提示】
//是否显示 气泡提示
const isLongTextPopShow = ref(false)
//鼠标进入检测字符区域后触发
function longTextMouseEnter() {
    const longTextAreaTarget = document.getElementsByClassName('longTextArea')[0]
    if (longTextAreaTarget){
        //获取显示宽度
        var containerWidth = parseFloat(window.getComputedStyle(longTextAreaTarget).width);
        //获取实际宽度
        var contentWidth = longTextAreaTarget.scrollWidth;
        if (contentWidth > containerWidth)
            isLongTextPopShow.value = true
    }
}
//================================================【生命周期】============================================================
</script>
<template>
    <div v-if="dataCheckReqParam.nrUnitCode" style="width: 100%;height: 100%">
        <div v-if="isMatchModel === false" class="rightInfoArea">
            <svg class="topIcon">
                <use xlink:href="#icon-100_ZT_E_NR_meiyouguanlianmoxing"></use>
            </svg>
            <div class="middleText_NonModel">无匹配模型</div>
        </div>
        <div v-else-if="dataCheckResType === undefined" class="rightInfoArea">
            <svg class="topIcon">
                <use xlink:href="#icon-100_ZT_E_NR_zanwuneirong"></use>
            </svg>
            <div class="middleText_NonContent">暂无分摊结果</div>
        </div>
        <div v-else-if="dataCheckResType === 'SUCCESS'" class="rightInfoArea">
            <svg class="topIcon">
                <use xlink:href="#icon-_Tchenggongtishi"></use>
            </svg>
            <div class="middleText_Success">审核成功</div>
            <j-tag style="width: 565px;height: 68px">
              <div class="bottomTag_Content">
                <div>
                  <svg class="bottomTag_Icon">
                    <use xlink:href="#icon-_Tchenggongtishi"></use>
                  </svg>
                  审核结束，结果无异常
                </div>
                <div class="bottomTag_modelAndCalculate" >
                  <j-poptip
                      :content="modelAndCalculateInfo.modelTitle"
                      trigger="custom"
                      :visible="isLongTextPopShow">
                    <div class="bottomTag_MAC_info longTextArea"
                         @mouseenter="longTextMouseEnter"
                         @mouseleave="isLongTextPopShow = false">
                      模型名称：{{ modelAndCalculateInfo.modelTitle }}
                    </div>
                  </j-poptip>
                  <div class="bottomTag_MAC_info">计算时间：{{ modelAndCalculateInfo.calculateTime }}</div>
                </div>
              </div>
            </j-tag>
        </div>
        <div v-else-if="dataCheckResType === 'CALCULATING'" class="rightInfoArea_calculating">
            <j-progress
                    :circle-size="65"
                    v-model:percent="calculateProgress"
                    type="circle"
            ></j-progress>
            <div class="middleText_Calculating">计算中</div>
        </div>
        <div v-else style="width: 100%;height: 100%">
            <div v-if="isGetMessageEnd && checkMessageArr.length > 0">
                <j-space size="large" style="height: 50px">
                    <j-poptip
                        :content="modelAndCalculateInfo.modelTitle"
                        trigger="custom"
                        :visible="isLongTextPopShow">
                        <div class="top_MAC_info longTextArea"
                             @mouseenter="longTextMouseEnter"
                             @mouseleave="isLongTextPopShow = false">
                            模型名称：{{ modelAndCalculateInfo.modelTitle }}
                        </div>
                    </j-poptip>
                    <div class="top_MAC_info">计算时间：{{ modelAndCalculateInfo.calculateTime }}</div>
                </j-space>
                <j-divider style="margin: unset"></j-divider>
                <j-collapse simple style="border: none">
                    <j-panel v-for="(check, index1) in checkMessageArr" :key="index1" class="checkPanelClass">
                        {{ check.validateType + '（' + check.validateDescription.length + '）' }}
                        <template #content>
                            <p
                                    v-for="(message, index2) in check.validateDescription"
                                    :key="index2"
                                    style="min-height:20px;
                                       height:auto !important;
                                       margin: 8px 0px 8px 0px"
                            >
                                {{ message }}
                            </p>
                        </template>
                    </j-panel>
                </j-collapse>
            </div>
            <div v-if="isGetMessageEnd && checkMessageArr.length === 0" class="rightInfoArea">
                    <svg class="topIcon">
                        <use xlink:href="#icon-_Tcuowutishi"></use>
                    </svg>
                    <div class="middleText_ErrorContent">审核出错</div>
                    <j-tag style="width: 565px;height: 68px">
                      <div class="bottomTag_Content">
                        <div>
                          <svg class="bottomTag_Icon">
                            <use xlink:href="#icon-_Tcuowutishi"></use>
                          </svg>
                          问题详情见日志。
                        </div>
                        <div class="bottomTag_modelAndCalculate">
                          <j-poptip
                              :content="modelAndCalculateInfo.modelTitle"
                              trigger="custom"
                              :visible="isLongTextPopShow">
                            <div class="bottomTag_MAC_info longTextArea"
                                 @mouseenter="longTextMouseEnter"
                                 @mouseleave="isLongTextPopShow = false">
                              模型名称：{{ modelAndCalculateInfo.modelTitle }}
                            </div>
                          </j-poptip>
                          <div class="bottomTag_MAC_info">计算时间：{{ modelAndCalculateInfo.calculateTime }}</div>
                        </div>
                      </div>
                    </j-tag>
            </div>
        </div>
    </div>
    <div v-else class="rightInfoArea">
        <svg class="topIcon">
            <use xlink:href="#icon-100_ZT_E_NR_zanwuneirong"></use>
        </svg>
        <div class="middleText_NonUnit">请选择单位</div>
    </div>
</template>

<style scoped>
.rightInfoArea {
    height: 100%;
    width: 100%;
    /*border: 1px red solid;*/
    flex-wrap: wrap;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-content: center;
    gap: 18px;
}

.rightInfoArea_calculating {
    padding-bottom: 97px;
    padding-left: 40px;
    height: 100%;
    width: 100%;
    flex-wrap: wrap;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-content: center;
    gap: 18px;
}
.top_MAC_info{
    max-width: 460px; /* 设置最大宽度 */
    height: 20px;

    font-family: PingFangSC-Regular;
    font-weight: 400;
    font-size: 14px;
    color: #424242;

    overflow: hidden; /* 隐藏超出容量的文本 */
    white-space: nowrap; /* 确保文本不会换行 */
    text-overflow: ellipsis; /* 显示省略号 */
}
.topIcon {
    width: 565px;
    height: 72px;
}

.middleText_NonUnit {
    margin-left: 230px;
    width: 301px;
    height: 28px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 20px;
    color: #0f0f0f;
}
.middleText_NonModel {
    margin-left: 234px;
    width: 100px;
    height: 28px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 20px;
    color: #0F0F0F;
}

.middleText_NonContent {
    margin-left: 224px;
    width: 301px;
    height: 28px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 20px;
    color: #0f0f0f;
}

.middleText_Success {
    margin-left: 241px;
    width: 83px;
    height: 28px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 20px;
    color: #0F0F0F;
    /*border: 1px red solid;*/
}
.middleText_ErrorContent {
    margin-left: 241px;
    width: 301px;
    height: 28px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 20px;
    color: #0f0f0f;
}
.middleText_Calculating {
    margin-left: 3px;
    width: 100px;
    height: 28px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 20px;
    color: #0F0F0F;
}
.checkPanelClass {
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 16px;
    color: #0F0F0F;
    border: none;
}

.checkPanelClass > :nth-child(1) {
    border-bottom: 1px #E5E5E5 solid !important;
}

.checkPanelClass > :nth-child(2) {
    padding: 0px 16px 16px 30px !important;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    font-size: 14px;
    color: #424242;
}
.bottomTag_Icon {
    margin-left: 25px;
    /*border: 1px red solid;*/
    width: 14px;
    height: 14px;
}
.bottomTag_Content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 565px;
  height: 68px;
  border-radius: 4px;
}
.bottomTag_modelAndCalculate{
    display: flex;
    flex-direction: column;
}
.bottomTag_MAC_info {
    width: 310px;
    height: 20px;

    font-family: PingFangSC-Regular;
    font-weight: 400;
    font-size: 14px;
    color: #424242;

    overflow: hidden; /* 隐藏超出容量的文本 */
    white-space: nowrap; /* 确保文本不会换行 */
    text-overflow: ellipsis; /* 显示省略号 */
}

</style>
